# coding:utf-8
# @Time : 2021/4/28 19:58
# @File : base.py

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String
from datetime import datetime

__all__ = ['db', 'BaseModel']

db = SQLAlchemy(use_native_unicode='utf8')


class BaseModel(db.Model):
    """
    基础的数据库模型，存放一些公共字段
    """
    __abstract__ = True

    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    create_time = Column(String(32), nullable=False, default=int(datetime.now().timestamp() * 1000))
    update_time = Column(String(32), nullable=False, default=int(datetime.now().timestamp() * 1000),
                         onupdate=int(datetime.now().timestamp() * 1000))

    def get_create_time(self):
        """
        获取数据创建时间
        :return: datetime类型，或者None
        """
        try:
            timestamp = int(self.create_time)
            return datetime.fromtimestamp(timestamp / 1000)
        except ValueError as e:
            import traceback
            traceback.print_exc()
            return None
